import axios from 'axios'
import store from '@/store'
import { MessageBox, Message } from 'element-ui'
import { getToken, setToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
	// dev环境：如果使用前端proxy，那么注释该路径。
	// url = base url + request url
	// baseURL: process.env.VUE_APP_BASE_API,
	// 跨域请求时发送cookies
	withCredentials: true,
	// 请求超时时间，单位为毫秒
	timeout: 20000
})

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent

		if(store.getters.token) {
			// 将 Token 加入请求头，这样就不需要每次都带 Token 参数了
			config.headers['Authorization'] = 'Bearer ' + getToken()
		}
		return config
	},
	error => {
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	 */

	/**
	 * 根据自定义状态确定请求状态
	 * 您还可以通过HTTP状态代码判断状态
	 */
	response => {
		const res = response.data

    let isToLogout = false
    // 40003:token已过期，请重新登录
    if(res.code === 40003) {
      if (res.data) {
        // 刷新token
        store.dispatch('user/refreshToken', res.data).then(() => {
          // 重新请求当前请求
          location.reload()
          //direct return
          // return Promise.reject(response)
        })
      } else {
        isToLogout = true
      }
    }

    // 40004:非法令牌；40005:无token，请重新登录；40007:token无效，请重新登录
    if(res.code === 40004 || res.code === 40005 || res.code === 40006 || res.code === 40007) {
      isToLogout = true
    }

    // to re-login
    if(isToLogout) {
      MessageBox.confirm('用户已失效，您可以取消以停留在此页，或重新登录', '确认注销', {
        confirmButtonText: '重新登录',
        cancelButtonText: '关闭',
        type: 'warning'
      }).then(() => {
        // 登出
        store.dispatch('user/logout').then(() => {
          location.reload()
        })
      })
    }

    return res
	},
	error => {
		return Promise.reject(error)
	}
)

export default service
